package com.ice.body.jwtFilter;

import com.ice.base.service.SysLoginService;
import com.ice.base.util.JwtUtil;
import com.ice.body.business.service.UserService;
import org.apache.shiro.util.AntPathMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


// 注入spring容器
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private static Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    private final SysLoginService sysLoginService;

    public JwtAuthenticationFilter(SysLoginService sysLoginService) {
        this.sysLoginService = sysLoginService;
    }
    /**
     * @param request
     * @param response
     * @param filterChain
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain) {

        response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));

        if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
            LOGGER.info("-----检查 {} ------", RequestMethod.OPTIONS.name());
            return;
        }
        try {
            if (false) {//isProtectedUrl(request)
                String token = request.getHeader("Authentication");

              /*  if (!"dev_token".equals(token)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "token已经被替换");
                    return;
                }*/
                if (token == null) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未匹配到token字段");
                    return;
                }
                //检查jwt令牌, 如果令牌不合法或者过期, 里面会直接抛出异常, 下面的catch部分会直接返回

               String opneId = JwtUtil.verifyToken(token);
          /*      UserModel model = userService.getByOpenId(opneId);
                if (model == null) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "用户信息异常");
                    return;
                }*/

//                if (oldTokenSet.contains(token)) {
//                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "token已经被替换");
//                    return;
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("一个 token 异常进来了" + HttpServletResponse.SC_UNAUTHORIZED + "," + e.getMessage());
            try {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return;
        }
        //如果jwt令牌通过了检测, 那么就把request传递给后面的RESTful api
        try {
            filterChain.doFilter(request, response);
        } catch (IOException | ServletException e) {
            e.printStackTrace();
        }

    }

    private boolean isProtectedUrl(HttpServletRequest request) {
        AntPathMatcher pathMatcher = new AntPathMatcher();
        return pathMatcher.match("/api/**", request.getServletPath());
    }

    private boolean isPublicUrl(HttpServletRequest request) {
        AntPathMatcher pathMatcher = new AntPathMatcher();
        return pathMatcher.match("/api_p/**", request.getServletPath());//获取验证码
    }
}
